import os
import sys
import shutil
import traceback
from tornado.web import RequestHandler
from tornado.ioloop import IOLoop


class SelfUpdateRequestHandler(RequestHandler):
    def post(self):
        # 文件的暂存路径
        upload_path = os.path.join(os.path.curdir, '.tmp')
        recover_path = os.path.join(os.path.curdir, '.recover')

        try:
            # 没有该文件夹则创建
            if not os.path.exists(upload_path):
                os.mkdir(upload_path)
            if not os.path.exists(recover_path):
                os.mkdir(recover_path)

            # 提取表单中'name'为'files'的文件元数据
            file_metas = self.request.files['files']
            for meta in file_metas:
                filename = meta['filename']
                filepath = os.path.abspath(os.path.join(upload_path, filename))

                # 生成路径
                os.makedirs(os.path.dirname(filepath), exist_ok=True)

                # 有些文件需要已二进制的形式存储，实际中可以更改
                with open(filepath, 'wb') as fd:
                    fd.write(meta['body'])

            # 移动所有除tmp外文件/文件夹到.recover
            for f in os.listdir(os.path.curdir):
                if f in [".recover", ".git", ".gitignore", "__pycache__", ".tmp"]:
                    continue
                shutil.move(f, recover_path)

            # 把文件全移动到工作目录
            for f in os.listdir(upload_path):
                shutil.move(os.path.join(upload_path, f), os.path.curdir)

            # 最后记得把临时文件删了
            os.rmdir(upload_path)
            shutil.rmtree(recover_path)

            # 报个成功
            self.finish({
                "code": 0,
                "message": "成功更新实例"
            })

            # 服务重启
            IOLoop.current().stop()
            os.execl(sys.executable, sys.executable, *sys.argv)

        except Exception:
            traceback.print_exc()

            # 恢复
            if os.path.exists(recover_path):
                for f in os.listdir(recover_path):
                    shutil.move(os.path.join(recover_path, f), os.path.curdir)

            self.finish({
                "code": -1,
                "message": "更新实例失败"
            })


self_update_handler_tuple = (r'/_self_update', SelfUpdateRequestHandler)
